package com.example.sixtrainingdemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sixtrainingdemo.R;
import com.example.sixtrainingdemo.database.DBHelper;
import com.example.sixtrainingdemo.entity.Shop;

import java.util.List;

public class ShopListAdapter extends BaseAdapter {
    private Context context;
    private List<Shop> shopList;
    private DBHelper dbHelper;


    public void updateData(List<Shop> shopList) {
        this.shopList = shopList;
        notifyDataSetChanged(); // 通知数据已改变
    }

    public ShopListAdapter(Context context, List<Shop> shopList) {
        this.context = context;
        this.shopList = shopList;
        this.dbHelper = DBHelper.getInstance(context);
    }

    @Override
    public int getCount() {
        return shopList.size();
    }

    @Override
    public Object getItem(int position) {
        return shopList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.shop_item, parent, false);
        }

        Shop shop = shopList.get(position);
        TextView textView1 = convertView.findViewById(R.id.shop_name);
        TextView textView2 = convertView.findViewById(R.id.shop_price);

        textView1.setText(shop.getName());
        textView2.setText(String.format("$ %.2f/%s", shop.getPrice(), shop.getUnit()));





        Button buttonDelete = convertView.findViewById(R.id.button_delete);
        buttonDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取点击事件中的shopId，例如从位置参数中获取
                int shopId = shopList.get(position).getId();
                // 调用deleteShop方法来删除shop表里的数据
                int rowsDeleted = dbHelper.deleteShop(shopId);
                if (rowsDeleted > 0) {
                    // 刷新列表
                    shopList.remove(position);
                    notifyDataSetChanged();
                    Toast.makeText(context, "商品删除成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "商品删除失败", Toast.LENGTH_SHORT).show();
                }
            }
        });

        return convertView;







    }
}
